const {
  http
} = require("../../../../utils/apiutils");

const app = getApp()
Page({

  data: {
    filter(type, options) {
      if (type === 'minute') {
        return options.filter(option => option== "00");
      }
      return options;
    },
    formatter(type, value) {
      if (type === 'minute') {
        return `${value}`;
      } 
      return value;
    },
    active: 0,
    sh: 0,
    limitTop: 0,
    limitBottom: 0,
    shs: 0,
    statusBar: 0,
    CustomBar: 0,
    canvasShow: false,
    limit: 10,
    itemHeight: 0,
    dataList: [],
    pageNo: 1,
    total: 1,
    latitude: 0,
    longitude: 0,
    action: 0,
    actionCur: {},
    option1: [{
        text: '小时',
        value: "小时"
      },
      {
        text: '天',
        value: "天"
      },
      {
        text: '月',
        value: "月"
      },
    ],
    option2: [{
        text: '不限',
        value: "不限"
      },
      {
        text: '男',
        value: "男"
      },
      {
        text: '女',
        value: "女"
      },
    ],
    option3: [{
        text: '不限',
        value: "不限"
      },
      {
        text: '大专',
        value: "大专"
      },
      {
        text: '本科',
        value: "本科"
      }
    ],
    value3: 0,
    fileList: [],
    value2: 0,
    minHour: 10,
    maxHour: 20,
    minDate: new Date().getTime(),
    maxDate: new Date(2019, 10, 1).getTime(),
    currentDate: new Date().getTime(),
    show: false,
    type: -1,
    fileListVideo: [],
    factoryJob: {
      type: 2,
      name: "",
      description: "",
      basicSalary: "",
      payType: "天",
      isPlay: 1,
      registerTime: "",
      asOfTime: "",
      startTime: "",
      leaveTime: "",
      sex: "不限",
      education: "不限"
    },
    fileListImg: [],
    fileListVideo: [],
    timestr: "",
    btype: -1,
    ptype: -1,
    fh: "",
    fh1: "",
    img: [],
    video: [],
  },
  onInput(event) {
    this.setData({
      currentDate: event.detail,
    });
  },
  onclcickShowAddress: function () {
    wx.navigateTo({
      url: '/pages/me/pages/address/address?type=1',
      success: (result) => {},
      fail: (res) => {},
      complete: (res) => {},
    })
  },
  onChangenumber: function (e) {
    this.data.factoryJob.number = e.detail;
  },
  onChangeFixedSalary: function (e) {
    this.data.factoryJob.fixedSalary = e.detail;
  },
  bindinputminAge: function (e) {
    this.data.factoryJob.minAge = e.detail.value;
  },
  bindinputmaxAge: function (e) {
    this.data.factoryJob.maxAge = e.detail.value;
  },
  onChangeName: function (e) {
    this.data.factoryJob.name = e.detail;
  },
  bindinputcontactPerson: function (e) {
    this.data.factoryJob.contactPerson = e.detail.value;
  },
  onChangefloatSalary: function (e) {
    this.data.factoryJob.floatSalary = e.detail;
  },
  bindinputcontactPhone: function (e) {
    this.data.factoryJob.contactPhone = e.detail.value;
  },
  onChangeDescription: function (e) {
    this.data.factoryJob.description = e.detail;
  },
  onChangeBasicSalary: function (e) {
    console.log(typeof e.detail)
    this.data.factoryJob.basicSalary = e.detail;
  },
  onclickType: function () {
    this.setData({
      factoryJob: {
        type: this.data.factoryJob.type == 1 ? "2" : "1"
      }
    })
    // this.data.factoryJob.type = this.data.factoryJob.type == 1?"2":"1"
  },
  deletaImg: function (e) {
    //  console.log("-----",e);
    let index = e.detail.index;
    this.data.fileListImg.splice(index, 1);
    this.setData({
      fileListImg: this.data.fileListImg,
    })
  },
  deletaVideo: function (e) {
    //  console.log("-----",e);
    let index = e.detail.index;
    this.data.fileListVideo.splice(index, 1);
    this.setData({
      fileListVideo: this.data.fileListVideo,
    })
  },
  afterRead1(event) {
    const {
      file
    } = event.detail;
    if (file.type == "video") {
      this.setData({
        afterRead(event) {
          const {
            file
          } = event.detail;
          if (file.type == "image") {
            this.setData({
              fileListVideo: [...this.data.fileListVideo, file],
            })
          } else {
            wx.showToast({
              title: '请上传图片文件',
            })
          }
          console.log("0000000", file);
        },
      })
    } else {
      wx.showToast({
        title: '请上传视频文件',
      })
    }
    // console.log("0000000", file);

  },




  sumbitData: function () {
    
    if (this.data.factoryJob.id) {
      http.updatePost(this.data.factoryJob,
        function (res) {
          wx.hideLoading()
          if (res.success) {
            wx.showModal({
              title: "提示",
              content: "修改岗位信息成功",
              showCancel: false,
              success: function () {
                wx.navigateBack({
                  delta: 1,
                })
              },
            })
          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })



    } else {
      console.log("--保存信息--")
      let params = JSON.parse(JSON.stringify( this.data.factoryJob))
      params.floatSalary = params.floatSalary * 100;
      params.fixedSalary = params.fixedSalary * 100;
      params.basicSalary = params.basicSalary * 100;
      var that = this;
      wx.showLoading({
        title: '加载中...',
      })
      params.registerTime = params.registerTime + ":00";
      params.asOfTime = params.asOfTime + ":00";
      params.startTime = params.startTime + ":00";
      params.leaveTime = params.leaveTime + ":00";
      // console.log(params)
      // return 
      http.addfactoryJob(params,
        function (res) {
          wx.hideLoading()
          if (res.success) {

            wx.showModal({
              title: "提示",
              content: "创建岗位成功,请耐心等待合作公司发布",
              showCancel: false,
              success: function () {
                wx.navigateBack({
                  delta: 1,
                })
              },
            })

          } else {
            wx.showToast({
              title: res.message,
              icon: "none",
            })
          }
        },
        function (err) {
          wx.hideLoading()
        })

    }

  },
  onlcickBack: function () {
    wx.navigateBack({
      delta: 1,
    })
  },
  onlcickSure: function () {

    console.log("-------", this.data.factoryJob);

    
    if (this.data.factoryJob.basicSalary > 1) {
      // this.data.factoryJob.basicSalary = this.data.factoryJob.basicSalary * 100
    } else {
      wx.showToast({
        title: '请填写对应的工资金额',
        icon: "none",
      })
      return
    }
    if (this.data.factoryJob.fixedSalary > 1) {
      // this.data.factoryJob.fixedSalary = this.data.factoryJob.fixedSalary * 100
    } else {
      wx.showToast({
        title: '请填写对应的奖金金额',
        icon: "none",
      })
      return
    }
    if (this.data.factoryJob.floatSalary > 1) {
      // this.data.factoryJob.floatSalary = this.data.factoryJob.floatSalary * 100
    } else {
      wx.showToast({
        title: '请填写对应的招聘费用',
        icon: "none",
      })
      return
    }

   
    //上传图片
    if (this.data.factoryJob.id) {
        this.sumbitData();
    } else {
      if (this.data.fileListImg.length > 0) {
        this.upDataFile(this.data.fileListImg, 0, 1)
      } else {
        wx.showToast({
          title: '工作必须上传工作相关一张封面照片',
          icon: "none",
        })
        return
      }
    }

    //  if(this.data.fileListVideo.length > 0)
    //   {
    //     this.upDataFile(this.data.fileListVideo, 0, 2)
    //   }
    //   else
    //   {
    //     this.sumbitData();
    //   }
  },
  upDataFile: function (data, index, type) {
    let item = data[index];
    console.log("-----", item);
    var that = this;
    var p = {
      url: item.url,
      name: "file",
      formData: {},
    }
    http.upDataFile(p,
      function (res) {
        console.log("---上传图片-", res);
        if (res.code == 0) {
          if (type == 1) {
            that.data.img.push(res.data);
            if (index == data.length - 1) {
              that.data.factoryJob.images = that.data.img;
              if (that.data.fileListVideo.length > 0) {
                that.upDataFile(that.data.fileListVideo, 0, 2)
              } else {
                that.sumbitData()
              }
            } else {
              console.log("--继续执行--", index, data.length - 1);
              that.upDataFile(data, index + 1, type)
            }
          } else if (type == 2) {
            that.data.video.push(res.data);
            if (index == data.length - 1) {
              that.data.factoryJob.video = that.data.video;
              that.sumbitData()
            } else {
              that.upDataFile(data, index + 1, type)
            }
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "nene",
          })
        }



      },
      function (err) {
        wx.hideLoading()
      })
  },
  afterRead(event) {
    const {
      file
    } = event.detail;
    if (file.type == "image") {
      this.setData({
        fileListImg: [...this.data.fileListImg, file],
      })
    } else {
      wx.showToast({
        title: '请上传图片文件',
      })
    }
    console.log("0000000", file);

  },
  onInput(event) {
    console.log(event)
    this.setData({
      currentDate: event.detail,
    });
  },
  change(event){
    console.log(event)
  },
  confirm: function (e) {
    if (this.data.btype != -1) {
      if (this.data.btype == 1) {
        var str = format(this.data.currentDate);
        this.setData({
          "factoryJob.registerTime": str+":00",
          timestr: "报名结束时间",
          btype: 2,
        })
        // console.log("------",this.data.currentDate)
      } else if (this.data.btype == 2) {
        var str = format(this.data.currentDate);
        this.setData({
          "factoryJob.asOfTime": str+":00",
          fh: " ~ ",
          show: false,
          btype: -1,
        })
        console.log("-----", this.data.factoryJob);
      }
    } else if (this.data.ptype != -1) {

      if (this.data.ptype == 1) {
        var str = format(this.data.currentDate);
        this.setData({
          "factoryJob.startTime": str+":00",
          timestr: "工作结束时间",
          ptype: 2,
        })
        // console.log("------",this.data.currentDate)
      } else if (this.data.ptype == 2) {
        var str = format(this.data.currentDate);
        this.setData({
          "factoryJob.leaveTime": str+":00",
          fh1: " ~ ",
          show: false,
          ptype: -1,
        })
        console.log("-----", this.data.factoryJob);
      }
    }
    // this.setData({
    //   show: false,
    // })
  },
  onclickSearch: function () {

    wx.navigateTo({
      url: '/pages/home/pages/search/search',
    })
  },
  onclickTime: function (e) {
    this.data.btype = 1;
    this.data.ptype = -1
    this.setData({
      timestr: "报名开始时间",
      show: true,
    })
  },
  onclickTime1: function (e) {
    this.data.btype = -1;
    this.data.ptype = 1
    this.setData({
      timestr: "工作开始时间",
      show: true,
    })
  },

  onClose: function () {
    if (this.data.btype != -1) {
      this.setData({
        factoryJob: {
          registerTime: "",
          asOfTime: "",
        },
        fh: "",
      })
    } else if (this.data.ptype != -1) {

    }
    this.setData({
      show: false,
    })
  },
  //检测活动距离
  scroll: function (e) {
    if (e.detail > this.data.CustomBar) {
      this.setData({
        ts: true,
      })
    } else {
      this.setData({
        ts: false,
      })
    }


    console.log("---------滑动距离---", e);
  },

  onclickInfo: function () {

    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?type=home',
            })
          }
        }
      })
      return;
    }

    if (this.data.action == 1) {
      if (this.data.actionCur.status == 4) {
        let data = {
          id: this.data.actionCur.id,
          name: this.data.actionCur.jobName,
          workplace: this.data.actionCur.workplace,
          type: 2,
          jobId: this.data.actionCur.jobId,
        }
        wx.navigateTo({
          url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
        })

      } else if (this.data.actionCur.status == 3) {
        // console.log("-------到岗打卡-----",item);
        // this.clockIn(item.id);
        var interviewDate = "";
        var str = this.data.actionCur.interviewDate;
        if (str) {
          str = str.substring(0, 19);
          str = str.replace(/-/g, '/');
          let date = new Date(str);
          interviewDate = date.getFullYear().toString() + "-" + (date.getMonth() + 1).toString() + "-" + date.getDate().toString(); // 年
        }
        let data = {
          id: this.data.actionCur.id,
          name: this.data.actionCur.jobName,
          workplace: this.data.actionCur.workplace,
          type: 1,
          jobId: this.data.actionCur.jobId,
          interviewDate: interviewDate,
        }
        wx.navigateTo({
          url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
        })


      } else {
        wx.navigateTo({
          url: '/pages/me/pages/action/action?type=3',
        })
      }


    } else {
      wx.navigateTo({
        url: '/pages/me/pages/action/action?type=3',
      })
    }

    // if (this.data.action == 1) {
    //   let item = this.data.actionCur;
    //   console.log("--------", item);
    //   let data = {
    //     id: item.id,
    //     name: item.jobName,
    //     workplace: item.workplace,
    //     type: 2,
    //     jobId: item.jobId
    //   }

    //   wx.navigateTo({
    //     url: '/pages/clockin/clockin?data=' + encodeURIComponent(JSON.stringify(data)),
    //   })
    // } else {
    //   wx.navigateTo({
    //     url: '/pages/me/pages/duty/duty',
    //   })
    // }


  },
  onclickCell: function (e) {
    if (!app.globalData.isLogin) {
      wx.showModal({
        title: "提示",
        content: "您还没有登录，登陆后即可查看详情",
        confirmText: "去登陆",
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login?ptype=home',
            })
          }
        }
      })
      return;
    }
    let item = e.currentTarget.dataset.item;
    // if (index % 2 == 0) {
    //   wx.navigateTo({
    //     url: '/pages/home/pages/train/train',
    //   })
    // } else {
    wx.navigateTo({
      url: '/pages/home/pages/work/work?id=' + item.id,
    })
    // }
  },

  onclickswiper: function (e) {

    let item = e.currentTarget.dataset.item;
    if (item.video) {
      wx.setStorageSync('video', JSON.stringify(item))
      wx.navigateTo({
        url: '/pages/home/pages/video/video',
      })
    } else {
      wx.showToast({
        title: '暂无详细介绍',
        icon: "none",
      })
    }

  },
  getJob() {
    var data = {
      "pageNo": this.data.pageNo, //手机号码
      "pageSize": "10" //密码
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getJob(data,
      function (res) {
        wx.hideLoading()
        console.log("------用户登录信息哦---", res);
        if (res.code == 0) {
          var pageNo = res.data.current;
          var total = res.data.pages;
          var arr = res.data.records;

          arr.forEach(element => {
            if (!that.data.latitude == 0) {
              let ds = util.getDistance(that.data.latitude, that.data.longitude, element.lat, element.lng);
              console.log("-----------", ds)
              if (element.stationFollow == 1) {
                element.dst = 0
              } else {
                element.dst = ds;
              }
              if (ds > 1) {
                element.ds = ds.toFixed(1) + "公里"
              } else {
                element.ds = (ds * 1000).toFixed(0) + "米"
              }
            } else {
              element.ds = "未知"
              element.dst = 0;
            }
          });
          arr = arr.sort(compare("dst"))
          if (pageNo == 1) {
            that.setData({
              dataList: arr,
              pageNo,
              total
            })
          } else if (pageNo <= total) {
            that.setData({
              dataList: [...that.data.dataList, ...arr],
              pageNo,
              total
            })
          }
        } else {
          wx.showToast({
            title: res.message,
            icon: "none",
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  onLoad: function (options) {
    var type = options.type
    var str = ""
    if (type == 1) {
      str = "修改岗位"
      var work = getApp().globalData.workInfo;
      var w = {
        id: work.id,
        address: work.address,
        asOfTime: work.asOfTime,
        basicSalary: work.basicSalary/100,
        contactPerson:work.contactPerson,
        contactPhone: work.contactPhone,
        description: work.description,
        education: work.education,
        fixedSalary:work.fixedSalary/100,
        floatSalary:work.floatSalary/100, 
        images:work.image.split(","),
        isPlay:work.isPlay,
        leaveTime: work.leaveTime,
        maxAge:work.maxAge,
        minAge:work.minAge,
        name: work.name,
        number:work.number,
        payType:work.payType,
        registerTime: work.registerTime,
        sex: work.sex,
        startTime: work.startTime,
      };
      this.setData({
        type: type,
        factoryJob:w,
      })
    } else if (type == 2) {
      str = "新增岗位";
      var work = getApp().globalData.workInfo;
      var w = {
        address: work.address,
        asOfTime: work.asOfTime,
        basicSalary: work.basicSalary/100,
        contactPerson:work.contactPerson,
        contactPhone: work.contactPhone,
        description: work.description,
        education: work.education,
        fixedSalary:work.fixedSalary/100,
        floatSalary:work.floatSalary/100, 
        images:work.image.split(","),
        isPlay:work.isPlay,
        leaveTime: work.leaveTime,
        maxAge:work.maxAge,
        minAge:work.minAge,
        name: work.name,
        number:work.number,
        payType:work.payType,
        registerTime: work.registerTime,
        sex: work.sex,
        startTime: work.startTime,
      }
      this.setData({
        type: type,
        factoryJob:w
      })
    } else {
      str = "新增岗位"
      this.setData({
        type: type,
      })
    }
    wx.setNavigationBarTitle({
      title: str,
    })
    return;
    this.getcarousel()
  },
  getcarousel: function () {
    var that = this;
    http.getcarousel({},
      function (res) {
        console.log("---轮播图-", res);
        if (res.code == 0) {
          var arr = res.data;
          that.setData({
            imgList: arr,
          })
        }
      },
      function (err) {
        wx.hideLoading()
      })


  },
  onReady: function () {

  },
  change: function (e) {
    this.setData({
      active: e.detail.index
    })
  },

  getclockInInfo: function () {
    var data = {
      "pageNo": 1,
      "pageSize": "10",
      "statusList": "3,4",
    }
    var that = this;
    wx.showLoading({
      title: '加载中...',
    })
    http.getregistration(data,
      function (res) {
        wx.hideLoading()
        console.log("------报名岗位列表---", res);
        if (res.code == 0) {
          var arr = res.data.records;
          if (arr.length == 1) {
            that.setData({
              actionCur: arr[0],
              action: 1
            })
          } else if (arr.length > 0) {
            that.setData({
              action: 2
            })
          }
        }
      },
      function (err) {
        wx.hideLoading()
      })

  },
  bindscrolltolower: function () {
    if (this.data.pageNo == this.data.total) {
      wx.showToast({
        title: '没有更多岗位了',
        icon: "none",
      })
    } else {
      this.data.pageNo = this.data.pageNo + 1;
      this.getJob()
    }

  },
  isGetSetting() {
    // 判断用户是否授权
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      success: function (res) {
        that.data.latitude = res.latitude;
        that.data.longitude = res.longitude;
        console.log("-----用户位置信息--", res)
        that.getJob();
      },
      fail: function (res) {
        wx.showToast({
          title: '您没有开启定位服务无法计算距离',
          icon: "none"
        })
        that.getJob();
      }
    })
    return
    wx.getSetting({
      success: (res) => {
        var statu = res.authSetting;
        if (!statu['scope.userLocation']) { //没授权

          return
          wx.showModal({
            title: '是否授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            confirmColor: '#f16765',
            success: res => {
              if (res.confirm) {
                wx.openSetting({
                  success: data => {
                    if (data.authSetting["scope.userLocation"]) {
                      // 调用百度地图，获取位置信息(就是经纬度转换成地址)
                      wx.getLocation({
                        type: 'gcj02',
                        success: function (res) {
                          console.log(res);
                          that.data.latitude = res.latitude;
                          that.data.longitude = res.longitude;
                          that.getJob();
                        },
                      })
                    }
                  }
                })
              } else {
                that.getJob();
              }
            }
          })
        } else { //已授权
          //做一些事情...

          wx.getLocation({
            type: 'gcj02',
            success: function (res) {
              that.data.latitude = res.latitude;
              that.data.longitude = res.longitude;
              console.log("-----用户位置信息--", res)
              that.getJob();
            },
            fail: function (res) {
              wx.showToast({
                title: '您没有开启定位服务无法计算距离',
                icon: "none"
              })
              that.getJob();
            }
          })
        }
      }
    })
  },

  onShow: function () {
    var that = this;
    let CustomBar = app.globalData.CustomBar;
    let statusBar = app.globalData.statusBar
    this.setData({
      CustomBar: CustomBar - statusBar,
      statusBar: statusBar,
    })
    wx.getSystemInfo({
      success: (result) => {
        var spx = 415 / 750 * result.windowWidth;
        that.setData({
          sh: result.windowHeight - CustomBar,
          shs: result.windowHeight - CustomBar - spx,
        })
      },
    })
    return;
    if (app.globalData.isLogin) {
      this.getclockInInfo();
    }
    this.isGetSetting();

  },
  onPageScroll() {

  },
  onPullDownRefresh: function () {
    this.onShow();
  },
})

function compare(property) {
  return function (a, b) {
    var value1 = a[property];
    var value2 = b[property];
    return value1 - value2;
  }
}

function add0(m) {
  return m < 10 ? '0' + m : m
}

function format(shijianchuo) {
  //shijianchuo是整数，否则要parseInt转换
  var time = new Date(shijianchuo);
  var y = time.getFullYear();
  var m = time.getMonth() + 1;
  var d = time.getDate();
  var h = time.getHours();
  // var mm = time.getMinutes();
  // var s = time.getSeconds();
  return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) //+ ':' + add0(mm) + ':' + add0(s);
}